package com.olap.starter.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;

/**
 * @author WBG
 * @date 2021/12/1 22:55
 * @describe http请求工具类
 */
public class HttpUtils {

    private static String charset = "UTF-8";
    private static int ConnectTimeout = 1000 * 30; //设置连接主机服务超时时间  默认30秒
    private static int ConnectionRequestTimeout = 1000 * 35; //设置连接请求超时时间 默认35秒
    private static int SocketTimeout = 1000 * 60; // 设置读取数据连接超时时间 默认60秒
    private static boolean applicationJson = false;

    /**
     * @param url
     * @return
     */
    public static String doGet(String url) throws IOException {
        return doGet(url, ConnectTimeout, ConnectionRequestTimeout, SocketTimeout, null);
    }

    public static String doGet(String url,String Authorization) throws IOException {
        return doGet(url, ConnectTimeout, ConnectionRequestTimeout, SocketTimeout, Authorization);
    }

    public static String doGet(String url, String headerName,String headerValue) throws IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通过址默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            // 设置请求头信息，鉴权
            if (headerName != null) {
                httpGet.setHeader(headerName, headerValue);
            }
            // 设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(ConnectTimeout)// 连接主机服务超时时间
                    .setConnectionRequestTimeout(ConnectionRequestTimeout)// 请求超时时间
                    .setSocketTimeout(SocketTimeout)// 数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            return EntityUtils.toString(entity);
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static String doGet(String url, int ConnectTimeout, int ConnectionRequestTimeout, int SocketTimeout, String Authorization) throws IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通过址默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            // 设置请求头信息，鉴权
            if (Authorization != null) {
                httpGet.setHeader("Authorization", Authorization);
            }
            // 设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(ConnectTimeout)// 连接主机服务超时时间
                    .setConnectionRequestTimeout(ConnectionRequestTimeout)// 请求超时时间
                    .setSocketTimeout(SocketTimeout)// 数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            return EntityUtils.toString(entity);
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static String doPost(String url, Map<String, Object> paramMap,String Authorization,boolean applicationJson) throws IOException {
        return doPost(url, paramMap, ConnectTimeout, ConnectionRequestTimeout, SocketTimeout, applicationJson,Authorization);
    }  public static String doPost(String url, Map<String, Object> paramMap) throws IOException {
        return doPost(url, paramMap, ConnectTimeout, ConnectionRequestTimeout, SocketTimeout, applicationJson,null);
    }

    /**
     * @param url
     * @param paramMap
     * @param ConnectTimeout           设置连接主机服务超时时间
     * @param ConnectionRequestTimeout 设置连接请求超时时间
     * @param SocketTimeout            设置读取数据连接超时时间
     * @param applicationJson          是否为json格式
     * @return
     */
    public static String doPost(String url, Map<String, Object> paramMap, int ConnectTimeout, int ConnectionRequestTimeout, int SocketTimeout, boolean applicationJson,String Authorization) throws IOException {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(ConnectTimeout)
                .setConnectionRequestTimeout(ConnectionRequestTimeout)
                .setSocketTimeout(SocketTimeout)
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        if (Authorization != null) {
            httpPost.setHeader("Authorization", Authorization);
        }
        // 设置请求头
        if (applicationJson) {
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        } else {
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        }

        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            // 为httpPost设置封装好的请求参数

            if (applicationJson) {
                //装填参数
                StringEntity stringEntity = new StringEntity(JSON.toJSONString(paramMap, false), charset);
                stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                httpPost.setEntity(stringEntity);
            } else {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                // 通过map集成entrySet方法获取entity
                Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
                // 循环遍历，获取迭代器
                Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, Object> mapEntry = iterator.next();
                    nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
            }

        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //HyLog.debug("POST-->："+url + "--->请求--结束:"+ SystemDateUtil.getTimeDifference(start)+"ms");
        }
        return result;
    }
}
